package com.vwa.BluetoothCalculate.Controller;

import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

public class BluetoothTest {

    private static final UUID uuid = new UUID("FFE0", true); // UUID for Serial Port Service
    private static String connectionString = null;

    public static void main(String[] args) throws BluetoothStateException, InterruptedException {
        // 获取本地蓝牙适配器
        LocalDevice localDevice = LocalDevice.getLocalDevice();
        System.out.println("本地蓝牙适配器: " + localDevice.getBluetoothAddress());

        // 开始设备发现
        final DiscoveryAgent agent = localDevice.getDiscoveryAgent();
        RemoteDevice[] devices = agent.retrieveDevices(DiscoveryAgent.PREKNOWN);
        if (devices != null) {
            for (RemoteDevice device : devices) {
                System.out.println("已发现设备: " + device.getBluetoothAddress());
            }
        } else {
            System.out.println("没有发现设备.");
        }

        // 选择设备（这里默认连接第一个设备）
        RemoteDevice selectedDevice = devices[0];
        connectionString = "btspp://" + selectedDevice.getBluetoothAddress() + ":" + uuid + ";authenticate=false;master=false";
        connectToDevice(connectionString);
    }

    private static void connectToDevice(String connectionString) {
        StreamConnection connection = null;
        try {
            // 建立连接
            connection = (StreamConnection) Connector.open(connectionString);
            System.out.println("连接成功!");

            // 进行数据传输（示例中省略具体操作）
            // InputStream in = connection.openInputStream();
            // OutputStream out = connection.openOutputStream();

            // 关闭连接
            connection.close();
            System.out.println("连接已关闭.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
